*** Set paths
local dir "..."
local dropbox_data "..."
local dropbox_data_create "..."
local local_data "..."
local dropbox_fig "..."
local dropbox_tab "..."


************************************************************
**** ASSING A HOME DEALER
************************************************************
 
preserve 
keep if trackclient=="market-wide" 
gen freq = 1
collapse (sum) IIROC_QUANTITY freq, by( LEI bidderid)

bys LEI: egen a10 = max(IIROC_QUANTITY)
bys LEI: egen a20 = total(IIROC_QUANTITY)
bys LEI: egen a1  = max(freq)
bys LEI: egen a2  = total(freq)
gen share  = freq/a2*100
gen shareq = IIROC_QUANTITY/a20*100

*define home dealer as the dealer with whom the investor trades most frequently with
bys LEI: egen max_share =max(share)
bys LEI: egen max_shareq =max(shareq)
gen homedealer  = (share>=max_share)
gen homedealer2 = (shareq>=max_shareq)
bys LEI: egen testing=total(homedealer)

*if there is are two home dealers with same share, use the share in quantity as criteria
replace homedealer=homedealer2 if testing>1
drop testing 
bys LEI: egen testing=total(homedealer)
count if testing>1 // should be zero

*for the one investor take one dealer at random
replace homedealer=0 if LEI=="30357000000" & bidderid==67
drop testing 
bys LEI: egen testing=total(homedealer)
count if testing>1 

gen homedealerID = bidderid if homedealer==1
bys LEI: egen a0 = 	max(homedealerID)
replace homedealerID = a0 if homedealerID==.

keep homedealer LEI bidderid homedealerID
tempfile tempHD
save  `tempHD' , replace
restore 

merge m:1 LEI bidderid using  `tempHD'
tab trackclient if _merge==1 // non-LEIs don't have a home dealer
replace homedealer=1 if _merge==1 // assume all anonymous clients and those with dealer id's trade with home dealer
replace homedealerID =bidderid if _merge==1
drop _merge 

*find out which LEI has trades only with the home dealer OTC
preserve
keep if trading_venue=="OTC"
collapse homedealer , by( LEI IIROC_SIDE )
gen only1d_otc = (homedealer==1) 
tempfile tempdealers
save  `tempdealers' , replace
restore 

merge m:1 LEI IIROC_SIDE using   `tempdealers' 
	tab trading_venue if _merge==1 // only candeal trades of LEIs who don't trade OTC
replace only1d_otc=0 if _merge==1 // fill them in as 0 because they don't have only 1 otc dealer	
drop _merge  


